<script setup lang="ts">
  import { register } from '~/apis/user'

  const toast = useToast()
  const route = useRoute()
  const router = useRouter()
  const loading = ref(false)
  const fields = [
    {
      name: 'username',
      type: 'text',
      label: '用户名',
      placeholder: '请输入用户名'
    },
    {
      name: 'nickname',
      type: 'text',
      label: '昵称',
      placeholder: '请输入昵称'
    },
    {
      name: 'password',
      label: '密码',
      type: 'password',
      placeholder: '请输入密码',
      showPassword: true
    },
    {
      name: 'confirmPassword',
      label: '确认密码',
      type: 'password',
      placeholder: '请输入确认密码',
      showPassword: true
    },
    {
      name: 'email',
      label: '邮箱',
      type: 'text',
      placeholder: '请输入邮箱（选填）'
    }
  ]

  const validate = (state: any) => {
    const errors = []
    if (!state.username) errors.push({ path: 'username', message: '用户名不能为空' })
    if (!state.nickname) errors.push({ path: 'nickname', message: '昵称不能为空' })
    if (!state.password) errors.push({ path: 'password', message: '密码不能为空' })
    if (state.password.length > 24 || state.password.length < 6)
      errors.push({ path: 'password', message: '密码为6-24位' })
    if (!state.confirmPassword)
      errors.push({ path: 'confirmPassword', message: '确认密码不能为空' })
    if (state.confirmPassword.trim() !== state.password.trim())
      errors.push({ path: 'confirmPassword', message: '两次密码不一致' })
    return errors
  }

  async function onSubmit(d: any) {
    try {
      loading.value = true
      const { data, pending } = await register(Object.assign({}, d))
      if (data.value) {
        toast.add({
          title: '注册成功，请登录',
          icon: 'i-heroicons-check-circle-solid',
          color: 'primary'
        })
        router.push({
          path: '/signin',
          query: route.query
        })
      }
      loading.value = pending.value
    } catch (error) {}
  }

  definePageMeta({
    layout: 'auth',
    middleware: 'auth'
  })

  useSeoMeta({
    title: '注册'
  })
</script>

<template>
  <UCard class="max-w-sm w-full bg-white/75 dark:bg-white/5 backdrop-blur">
    <UAuthForm
      :fields="fields"
      :validate="validate"
      align="top"
      title="创建账户"
      :ui="{ base: 'text-center', footer: 'text-center' }"
      :submit-button="{ label: '注册' }"
      @submit="onSubmit"
    >
      <template #description>
        已经有账户了?
        <NuxtLink
          :to="$route.query.redirect ? '/signin?redirect=' + $route.query.redirect : '/signin'"
          class="text-primary font-medium"
          >登录</NuxtLink
        >
      </template>
    </UAuthForm>
  </UCard>
</template>
